package com.ah.proj.bus.address.servlet;

import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import com.ah.proj.bean.Address;
import com.ah.proj.bus.address.service.AddressService;
import com.ah.proj.util.BaseServlet;
import com.ah.proj.util.Const;

@WebServlet("/AddressServlet")
public class AddressServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private AddressService service = new AddressService();

	protected void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 查询全部信息（不一定是完整信息）
		List<Address> productList = service.getAll();
		// 存入域对象中
		request.getSession().setAttribute("list", productList);
		// 页面跳转
		response.sendRedirect(Const.PAGE_ADDR_LIST);
	}

	protected void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		boolean delete = service.delete(Integer.valueOf(id));
		if (!delete) {
			request.setAttribute("msg", "操作失败");
		}
		// 重新查询
		response.sendRedirect(Const.ACTION_LIST);
	}

	protected void add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 页面跳转
		response.sendRedirect(Const.PAGE_DETAIL);
	}

	protected void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String strId = request.getParameter("id");
		int id = Integer.valueOf(strId);
		// 根据id获取完整对象信息
		Address addr = service.getById(id);
		// 把对象存入Request
		request.setAttribute("addr", addr);
		// 页面跳转
		request.getRequestDispatcher(Const.PAGE_DETAIL).forward(request, response);
	}

	protected void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String strId = request.getParameter("id");
		System.out.println(strId);
		String address = request.getParameter("address");
		String tel = request.getParameter("tel");
		Address addr = new Address();
		if (strId == null || "".contentEquals(strId)) {
			// 新增的场合
			addr.setId(-1);
		} else {
			// 更新的场合（新增时不用管isDelete字段，但更新包括逻辑删除，需要设置）
			addr.setId(Integer.valueOf(strId));
			addr.setIsDelete("0");
		}
		addr.setAddress(address);
		addr.setTel(tel);
		boolean save = service.save(addr);
		if (!save) {
			request.setAttribute("msg", "操作失败");
		}
		// 重新查询
		response.sendRedirect(Const.ACTION_LIST);
	}

}